package com.zhengshang.web.controller.app;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhengshang.api.domain.AppThirdColumn;
import com.zhengshang.api.domain.AppThirdColumnCategory;
import com.zhengshang.api.service.IAppThirdColumnCategoryService;
import com.zhengshang.api.service.IAppThirdColumnService;
import com.zhengshang.common.utils.SecurityUtils;
import com.zhengshang.common.utils.StringUtils;
import com.zhengshang.common.utils.ip.IpUtils;
import com.zhengshang.system.service.ISysConfigService;
import com.zhengshang.third.wikeyun.WikeyunApi;
import com.zhengshang.third.wikeyun.WikeyunUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.zhengshang.common.annotation.Log;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.enums.BusinessType;
import com.zhengshang.api.domain.AppBillProduct;
import com.zhengshang.api.service.IAppBillProductService;
import com.zhengshang.common.utils.poi.ExcelUtil;
import com.zhengshang.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 话费商品Controller
 *
 * @author zhengshang
 * @date 2021-06-07
 */
@RestController
@RequestMapping("/app/product")
public class AppBillProductController extends BaseController {
    @Autowired
    private IAppBillProductService appBillProductService;

    @Autowired
    private IAppThirdColumnService thirdColumnService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IAppThirdColumnCategoryService appThirdColumnCategoryService;

    @Autowired
    private WikeyunUtils wikeyunUtils;

    /**
     * 查询话费商品列表
     */
    @PreAuthorize("@ss.hasPermi('app:product:list')")
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam(required = false) Map params) {
        startPage();
        String productTypes = (String) params.get("productTypes");
        if (StringUtils.isNotEmpty(productTypes)) {
            String[] split = productTypes.split(",");
            params.put("productTypes", split);
        }
        List<AppBillProduct> list = appBillProductService.selectAppBillProductList2(params);
        return getDataTable(list);
    }

    /**
     * 查询影音商品列表
     */
    @PreAuthorize("@ss.hasPermi('app:product:list')")
    @GetMapping("/list1")
    public TableDataInfo list1(@RequestParam(required = false) Map params) {
        startPage();
        String productTypes = (String) params.get("productTypes");
        if (StringUtils.isNotEmpty(productTypes)) {
            String[] split = productTypes.split(",");
            params.put("productTypes", split);
        }
        List<Map> list = appBillProductService.selectAppBillProductList1(params);
        return getDataTable(list);
    }

    /**
     * 导出话费商品列表
     */
    @PreAuthorize("@ss.hasPermi('app:product:export')")
    @Log(title = "话费商品", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(AppBillProduct appBillProduct) {
        List<AppBillProduct> list = appBillProductService.selectAppBillProductList(appBillProduct);
        ExcelUtil<AppBillProduct> util = new ExcelUtil<AppBillProduct>(AppBillProduct.class);
        return util.exportExcel(list, "product");
    }

    /**
     * 获取话费商品详细信息
     */
    @PreAuthorize("@ss.hasPermi('app:product:query')")
    @GetMapping(value = "/{billId}")
    public AjaxResult getInfo(@PathVariable("billId") Long billId) {
        return AjaxResult.success(appBillProductService.selectAppBillProductById(billId));
    }

    /**
     * 新增话费商品
     */
    @PreAuthorize("@ss.hasPermi('app:product:add')")
    @Log(title = "话费商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppBillProduct appBillProduct) {
        appBillProduct.setCreateBy(SecurityUtils.getUsername());
        return toAjax(appBillProductService.insertAppBillProduct(appBillProduct));
    }

    /**
     * 修改话费商品
     */
    @PreAuthorize("@ss.hasPermi('app:product:edit')")
    @Log(title = "话费商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppBillProduct appBillProduct) {
        appBillProduct.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(appBillProductService.updateAppBillProduct(appBillProduct));
    }

    /**
     * 删除话费商品
     */
    @PreAuthorize("@ss.hasPermi('app:product:remove')")
    @Log(title = "话费商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{billIds}")
    public AjaxResult remove(@PathVariable Long[] billIds) {
        return toAjax(appBillProductService.deleteAppBillProductByIds(billIds));
    }

    /**
     * 同步微客云集产品数据
     */
    @Log(title = "同步微客云集产品数据", businessType = BusinessType.INSERT)
    @PostMapping("syscWiKeYunProduct")
    public AjaxResult syscWiKeYunProduct(HttpServletRequest request, Long thirdColumnId) {
        AppThirdColumn appThirdColumn = thirdColumnService.selectAppThirdColumnById(thirdColumnId);
        Integer thirdColumnSyscstate = appThirdColumn.getThirdColumnSyscstate();
        if (thirdColumnSyscstate == 1) {
            return AjaxResult.error("该分类已同步过");
        }
        Long wikeyunServerid = appThirdColumn.getWikeyunServerid();
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("id", wikeyunServerid);
        params.put("ip", IpUtils.getIpAddr(request));
        String result = wikeyunUtils.sendPostRequest(params, WikeyunApi.getThirdProInfo);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if ("0000".equals(code)) {
            JSONObject data = jsonObject.getJSONObject("data");
            JSONObject proInfo = data.getJSONObject("pro_info");
            String accountType = proInfo.getString("account_type");
            JSONArray specJSONArray = proInfo.getJSONArray("spec");
            for (int i = 0; i < specJSONArray.size(); i++) {
                JSONObject jsonObject1 = specJSONArray.getJSONObject(i);
                String specTitle = jsonObject1.getString("spec_title");
                AppThirdColumnCategory appThirdColumnCategory = new AppThirdColumnCategory();
                appThirdColumnCategory.setThirdColumnId(thirdColumnId);
                appThirdColumnCategory.setThirdColumnCategoryName(specTitle);
                appThirdColumnCategory.setThirdColumnCategorySort(i + 1);
                int i1 = appThirdColumnCategoryService.insertAppThirdColumnCategory(appThirdColumnCategory);
                if (i1 > 0) {
                    Long thirdColumnCategoryId = appThirdColumnCategory.getThirdColumnCategoryId();
                    JSONArray specList = jsonObject1.getJSONArray("spec_list");
                    for (int j = 0; j < specList.size(); j++) {
                        JSONObject jsonObject2 = specList.getJSONObject(j);
                        String times = jsonObject2.getString("times");
                        String productName = "";
                        if ("7天".equals(times)) {
                            productName = "周卡";
                        } else if ("1个月".equals(times)) {
                            productName = "月卡";
                        } else if ("3个月".equals(times)) {
                            productName = "季卡";
                        } else if ("6个月".equals(times)) {
                            productName = "半年卡";
                        } else if ("1年".equals(times)) {
                            productName = "年卡";
                        } else {
                            productName = times;
                        }
                        //给平台用户的成本价
                        BigDecimal cmsPrice = jsonObject2.getBigDecimal("cms_price");
                        String productImg = jsonObject2.getString("spec_img");
                        //划线价
                        BigDecimal officialPrice = jsonObject2.getBigDecimal("official_price");
                        String spec_id = jsonObject2.getString("spec_id");
                        AppBillProduct appBillProduct = new AppBillProduct();
                        appBillProduct.setProductType(appThirdColumn.getThirdColumnType());
                        appBillProduct.setMobileFuluProductName(productName);
                        String desc = jsonObject2.getString("title") + "_" + times;
                        appBillProduct.setProductDesc(desc);
                        appBillProduct.setProductImg(productImg);
                        //成本价
                        appBillProduct.setMobileMoneyCost(cmsPrice);
                        //价格
                        appBillProduct.setMoney(cmsPrice.add(new BigDecimal(3)));
                        //划线价
                        appBillProduct.setMobileMoneyPrice(officialPrice);
                        appBillProduct.setProductSort(j + 1);
                        appBillProduct.setMobileFuluProductId(spec_id);
                        appBillProduct.setThirdColumnId(thirdColumnId);
                        appBillProduct.setThirdColumnCategoryId(thirdColumnCategoryId);
                        appBillProductService.insertAppBillProduct(appBillProduct);
                    }
                }

            }
            appThirdColumn.setThirdColumnSyscstate(1);
            thirdColumnService.updateAppThirdColumn(appThirdColumn);
            return AjaxResult.success();
        } else {
            String msg = jsonObject.getString("msg");
            return AjaxResult.error("获取微客云集数据失败,原因" + msg);
        }
    }

    /**
     * 更新微客云集产品数据
     */
    @Log(title = "更新微客云集产品数据", businessType = BusinessType.UPDATE)
    @PostMapping("updateWiKeYunProduct")
    public AjaxResult updateWiKeYunProduct(HttpServletRequest request, Long thirdColumnId) {
        AppThirdColumn appThirdColumn = thirdColumnService.selectAppThirdColumnById(thirdColumnId);
        Long wikeyunServerid = appThirdColumn.getWikeyunServerid();
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("id", wikeyunServerid);
        params.put("ip", IpUtils.getIpAddr(request));
        String result = wikeyunUtils.sendPostRequest(params, WikeyunApi.getThirdProInfo);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if ("0000".equals(code)) {
            JSONObject data = jsonObject.getJSONObject("data");
            JSONObject proInfo = data.getJSONObject("pro_info");
            JSONArray specJSONArray = proInfo.getJSONArray("spec");

            for (int i = 0; i < specJSONArray.size(); i++) {
                JSONObject jsonObject1 = specJSONArray.getJSONObject(i);
                JSONArray specList = jsonObject1.getJSONArray("spec_list");

                for (int j = 0; j < specList.size(); j++) {
                    JSONObject jsonObject2 = specList.getJSONObject(j);
                    String spec_id = jsonObject2.getString("spec_id");
                    AppBillProduct appBillProduct = appBillProductService.selectWeiKeYunProduct(spec_id, thirdColumnId);
                    String times = jsonObject2.getString("times");
                    String productName = "";
                    if ("7天".equals(times)) {
                        productName = "周卡";
                    } else if ("1个月".equals(times)) {
                        productName = "月卡";
                    } else if ("3个月".equals(times)) {
                        productName = "季卡";
                    } else if ("6个月".equals(times)) {
                        productName = "半年卡";
                    } else if ("1年".equals(times)) {
                        productName = "年卡";
                    } else {
                        productName = times;
                    }
                    if (ObjectUtils.isNotEmpty(appBillProduct)) {
                        //给平台用户的成本价
                        BigDecimal cmsPrice = jsonObject2.getBigDecimal("cms_price");

                        //成本价
                        appBillProduct.setMobileMoneyCost(cmsPrice);
                        BigDecimal official_price = jsonObject2.getBigDecimal("official_price");
                        appBillProduct.setMoney(official_price);

                        appBillProduct.setMobileFuluProductName(productName);
                        BigDecimal proportion = new BigDecimal(configService.selectConfigByKey("app.proportion", "1.05"));
                        appBillProduct.setMobileMoneyPrice(cmsPrice.multiply(proportion).setScale(1, BigDecimal.ROUND_HALF_UP));
                        appBillProductService.updateAppBillProduct(appBillProduct);
                    } else {
                        String specTitle = jsonObject1.getString("spec_title");
                        AppThirdColumnCategory appThirdColumnCategory = appThirdColumnCategoryService.selectAppThirdColumnCategoryByName(specTitle);
                        if (ObjectUtils.isEmpty(appThirdColumnCategory)) {
                            appThirdColumnCategory = new AppThirdColumnCategory();
                            appThirdColumnCategory.setThirdColumnId(thirdColumnId);
                            appThirdColumnCategory.setThirdColumnCategoryName(specTitle);
                            appThirdColumnCategory.setThirdColumnCategorySort(i + 1);
                            appThirdColumnCategoryService.insertAppThirdColumnCategory(appThirdColumnCategory);
                        }
                        Long thirdColumnCategoryId = appThirdColumnCategory.getThirdColumnCategoryId();
                        //给平台用户的成本价
                        BigDecimal cmsPrice = jsonObject2.getBigDecimal("cms_price");
                        String productImg = jsonObject2.getString("spec_img");
                        //划线价
                        BigDecimal officialPrice = jsonObject2.getBigDecimal("official_price");
                        AppBillProduct newAppBillProduct = new AppBillProduct();
                        newAppBillProduct.setProductType(appThirdColumn.getThirdColumnType());
                        newAppBillProduct.setMobileFuluProductName(productName);
                        String desc = jsonObject2.getString("title") + "_" + times;
                        newAppBillProduct.setProductDesc(desc);
                        newAppBillProduct.setProductImg(productImg);
                        //成本价
                        newAppBillProduct.setMobileMoneyCost(cmsPrice);
                        //价格
                        newAppBillProduct.setMoney(cmsPrice.add(new BigDecimal(3)));
                        //划线价
                        newAppBillProduct.setMobileMoneyPrice(officialPrice);
                        newAppBillProduct.setProductSort(j + 1);
                        newAppBillProduct.setMobileFuluProductId(spec_id);
                        newAppBillProduct.setThirdColumnId(thirdColumnId);

                        newAppBillProduct.setThirdColumnCategoryId(thirdColumnCategoryId);
                        appBillProductService.insertAppBillProduct(newAppBillProduct);
                    }
                }
            }
            return AjaxResult.success();
        } else {
            String msg = jsonObject.getString("msg");
            return AjaxResult.error("获取微客云集数据失败,原因" + msg);
        }
    }

}
